package cn.le.netty.client.handler;

import cn.le.netty.beans.EnumMsgCode;
import cn.le.netty.beans.Member;
import cn.le.netty.beans.NettyMsg;
import cn.le.util.InputUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import org.msgpack.MessagePack;

import java.util.UUID;

/**
 * 需要进行数据读取操作,服务器处理完成的数据信息进行读取
 */
public class EchoClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端发送消息");
        NettyMsg msg = new NettyMsg();
        msg.setId(UUID.randomUUID().toString());
        msg.setfUid(2);
        msg.settUid(1);
        msg.setContent("你好");
        msg.setCode(EnumMsgCode.login.getCode());
        ctx.writeAndFlush(msg);
    }

    //处理字符串
   /* @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //只要服务器发送完成消息之后,都会执行此方法进行内容的输出操作
        try {
            String readData = msg.toString().trim();
            if ("quit".equalsIgnoreCase(readData)){
                System.out.println("[exit] 已经结束本次通信");
                ctx.close();
            }else {
                System.out.println(readData);//输出服务器的响应内容
                String inputdata = InputUtil.getString("数据发送消息");
                inputdata = inputdata + System.getProperty("line.separator");//添加拆包标志符
                ctx.writeAndFlush(inputdata);
            }
        }finally {
            ReferenceCountUtil.release(msg);
        }
    }*/
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //只要服务器发送完成消息之后,都会执行此方法进行内容的输出操作
        try {
            System.out.println(msg);
        } finally {
            ReferenceCountUtil.release(msg);//释放消息
        }
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
